package com.newgoldcurrency.activities.register;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.collection.ArraySet;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.bean.UserBean;
import com.newgoldcurrency.databinding.ActivityRegisterMeBinding;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;
import com.newgoldcurrency.view.LoadingDialog;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class RegisterMeActivity extends AppCompatActivity {
    private final ArraySet<Call> calls=new ArraySet<>();
    private ActivityRegisterMeBinding binding;
    private LoadingDialog loading_dialog;
    private ActivityResultLauncher<Intent> launcher;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRegisterMeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setResult(1);
        binding.registerMeClose.setOnClickListener(v -> finish());
        loading_dialog=new LoadingDialog(this);
        binding.registerMeRegister.setOnClickListener(v -> {
            if (checkDoubleClick()) {
                launcher.launch(new Intent(RegisterMeActivity.this,RegisterVerifyActivity.class));
            }
        });

        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode()==3){
                if (loading_dialog != null && !loading_dialog.isShowing()) {
                    loading_dialog.show();
                    String my_code = binding.registerMeMyCode.getText().toString();
                    if (my_code.equals("")){
                        Tools.toast(getString(R.string.input_your_code));
                        loading_dialog.dismiss();
                        return;
                    }
                    if (!Tools.isCode(my_code)){
                        Tools.toast(getString(R.string.invitation_code_format_err));
                        loading_dialog.dismiss();
                        return;
                    }
                    String friend_code = getIntent().getStringExtra("friend_code");
                    String password = getIntent().getStringExtra("password");
                    String country = getIntent().getStringExtra("country");
                    String email = getIntent().getStringExtra("email");
                    HashMap<String, String> map=new HashMap<>();
                    map.put("mail",email);
                    map.put("password",password);
                    map.put("country",country);
                    map.put("invitationCode",my_code);
                    map.put("superCode",friend_code);
                    String id= Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
                    map.put("imei",id);
                    if (id==null){
                        Tools.toast("Your device is not recognized");
                        loading_dialog.dismiss();
                    }else if (id.equals("")){
                        Tools.toast("Your device is not recognized");
                        loading_dialog.dismiss();
                    }else {
                        Network.post(map,"user/register", call1 -> {
                            call1.enqueue(new Callback(){
                                @Override
                                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                    runOnUiThread(() -> {
                                        e.printStackTrace();
                                        loading_dialog.dismiss();
                                    });
                                }
                                @Override
                                public void onResponse(@NonNull Call call, @NonNull Response response) {
                                    runOnUiThread(() -> {
                                        loading_dialog.dismiss();
                                        try {
                                            String str= Objects.requireNonNull(response.body()).string();
                                            if (Tools.isJson(str)){
                                                JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
                                                if (jo.get("message").getAsString().equals("Register success")){
                                                    JsonObject user = jo.getAsJsonObject("data").get("user").getAsJsonObject();
                                                    App.userBean =new UserBean();
                                                    App.userBean.mail=user.get("mail").getAsString();
                                                    App.userBean.id=user.get("id").getAsString();
                                                    App.userBean.invitation_code=user.get("invitation_code").getAsString();
                                                    SharedPreferences.Editor edit = App.sp.edit();
                                                    edit.putString("token",jo.getAsJsonObject("data").get("token").getAsString());
                                                    edit.apply();
                                                    setResult(2);
                                                    finish();
                                                }else {
                                                    Tools.toast(jo.get("message").getAsString());
                                                }
                                            }
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    });
                                }
                            });
                            calls.add(call1);
                        });
                    }
                }
            }
        });

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Call call:calls) call.cancel();
        binding=null;
    }
    private long mClickTime;
    private boolean checkDoubleClick() {
        boolean result= mClickTime < SystemClock.uptimeMillis() - 500;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }
}